package cn.wellwhz.VoteForNight;

import cn.nukkit.Player;
import cn.nukkit.event.EventHandler;
import cn.nukkit.event.Listener;
import cn.nukkit.event.player.PlayerBedEnterEvent;
import cn.nukkit.event.player.PlayerBedLeaveEvent;
import cn.nukkit.level.Level;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EnterBedEventListener implements Listener {
    private final Map<Level, List<Player>> playerInBed = new HashMap<>();
    private final VoteForNight ins = VoteForNight.getInstance();

    @EventHandler
    private void onPlayerEnterBed(PlayerBedEnterEvent ent) {
        Player p = ent.getPlayer();
        Level l = p.getLevel();
        if (!ins.getConfig().getStringList("插件开启世界").contains(l.getName())) {
            return;
        }
        if (!playerInBed.containsKey(l)) {
            playerInBed.put(l, new ArrayList<>());
        }
        playerInBed.put(l, Utils.addToList(playerInBed.get(l), p));
        for (Player player : l.getPlayers().values()) {
            player.sendMessage("§a玩家" + p.getName() + " 已入睡，已有 " + playerInBed.get(l).size() + "/" + l.getPlayers().size() + " 名玩家入睡");
        }
        if (playerInBed.get(l).size() >= l.getPlayers().size() / 2) {
            ins.getServer().getScheduler().scheduleDelayedTask(new WakeUpPlayerTask(playerInBed.get(l).toArray(new Player[]{}), l, this), 100);
        }
    }

    @EventHandler
    private void onPlayerLeaveBed(PlayerBedLeaveEvent ent) {
        Player p = ent.getPlayer();
        Level l = p.getLevel();
        if (!ins.getConfig().getStringList("插件开启世界").contains(l.getName())) {
            return;
        }
        if (!playerInBed.containsKey(l) || l.getTime() == 24000) {
            playerInBed.put(l, new ArrayList<>());
        }
        if (playerInBed.get(l).contains(p)) {
            playerInBed.put(l, Utils.removeFromList(playerInBed.get(l), p));
            if (l.getTime() != 24000) {
                for (Player player : l.getPlayers().values()) {
                    player.sendMessage("§a玩家" + p.getName() + " 已离开床，已有 " + playerInBed.get(l).size() + "/" + l.getPlayers().size() + " 名玩家入睡");
                }
            } else {
                for (Player player : l.getPlayers().values()) {
                    player.sendMessage("§a已投票跳过夜晚");
                }
            }
        }
    }

    public void clearLevel(Level l) {
        playerInBed.put(l, new ArrayList<>());
    }
}
